package com.decoration.basic.controller.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.druid.util.StringUtils;
import com.decoration.basic.entity.*;
import com.decoration.basic.po.DecCtctionInfVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.decoration.basic.BasicController;
import com.decoration.basic.mapper.DecPictureMapper;
import com.decoration.basic.findCondition.DecDailyFindCondition;
import com.decoration.basic.service.DecDailyService;
import com.decoration.basic.service.DecUserService;
import com.decoration.basic.util.DateFormatUtils;
import com.decoration.basic.util.Global;
import com.decoration.basic.util.SnowFlake;

@RestController
@RequestMapping("/api")
public class DecDailyController extends BasicController{

	private static Logger log = LoggerFactory.getLogger(DecDailyController.class);

	@Autowired
	private DecDailyService decDailyService;

	@Resource
	private DecUserService decUserService;

	// 用户获取日报列表
	@RequestMapping(value = "/daily/list", method = RequestMethod.POST)
	public JsonResult dailylist(JsonResult jsonResult, @RequestBody DecDailyFindCondition findCondition, HttpSession session) {
		// 1.校验用户信息
		String userid = null;
		try {
			userid = session.getAttribute(Global.SESSION_USER_ID).toString();
		} catch (Exception e) {
			log.error("获取用户id异常");
		}
		if (StringUtils.isEmpty(userid)) {

			jsonResult.setCode(JsonResult.FAILED_ACCOUNT_ABNORMAL);
			jsonResult.setMsg("无登录信息，请重新登陆");
			jsonResult.setData(new ArrayList<>());
			return jsonResult;
		}

		DecorationUser userinfo = null;
		try {
			userinfo = decUserService.findById(userid);
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("查询用户信息失败，请联系管理员");
			return jsonResult;
		}
		if (userinfo == null){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("无可用登录信息，请重新登陆");
			return jsonResult;
		}
		// 游客不可以获取日报信息
		if (userinfo.getPerType() == 5) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("您无日报可查");
			jsonResult.setData(new ArrayList<>());
			return jsonResult;
		}
		//2.如果是监理或者业主，校验该用户是否属于此项目--前端控制，不做校验
		//如果是师傅，查询添加用户id
		if (userinfo.getPerType() != 1){
			findCondition.setUserId(null);
		}
		//3.校验工地id信息
		if (StringUtils.isEmpty(findCondition.getCtcId())){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("输入项目编号为空");
			jsonResult.setData(new ArrayList<>());
			return jsonResult;
		}
		if (StringUtils.isEmpty(findCondition.getCurdate())){
			findCondition.setCurdate(null);
		}
		//添加分页信息
		setPagerInfo(findCondition);
		// 4.校验数据库信息
		List<DecDailyOutMsg> list = new ArrayList<>();
		int sum = 0;
		try {
			//设置分页信息，mabatis 拦截器拼接sql分页参数
			PageHelper.startPage(findCondition.getPage(), findCondition.getDataCount());
			list = decDailyService.getDailyList(findCondition);
			PageInfo<DecDailyOutMsg> pageInfo = new PageInfo(list);
			sum = Integer.parseInt(String.valueOf(pageInfo.getTotal()));
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("获取日报列表失败!");
			jsonResult.setCount(sum);
			jsonResult.setData(new ArrayList<>());
			return jsonResult;
		}

		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setCount(sum);
		if (list.size() == 0){
            jsonResult.setMsg("获取日报列表为空!");
			jsonResult.setData(new ArrayList<>());
            return jsonResult;
        }

		jsonResult.setMsg("获取日报列表成功!");
		jsonResult.setData(list);
		return jsonResult;
	}


	/**
	 * 用户页面-获取日报内容
	 * @param jsonResult
	 * @param findCondition
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/daily/dailyId", method = RequestMethod.POST)
	public JsonResult dailybyCurdate(JsonResult jsonResult, @RequestBody DecorationDailyInf findCondition, HttpServletRequest request) {
		//1.校验用户信息
		String userid = null;
		try {
			userid = (String)request.getSession().getAttribute(Global.SESSION_USER_ID);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(StringUtils.isEmpty(userid)){
			jsonResult.setCode(JsonResult.FAILED_UNLGIN);
			jsonResult.setMsg("无用户登录信息,跳转登录页面");
			return jsonResult;
		}
		log.info("登录用户id : " + userid);
		DecorationUser user = decUserService.findById(userid);
		if (user == null){
			jsonResult.setCode(JsonResult.FAILED_UNPERMISSION);
			jsonResult.setMsg("无用户信息,此用户无权限，跳转登录页面");
			return jsonResult;
		}

		//2.获取日报信息
		DecorationDailyInf list = null;
		try {
			list = decDailyService.findById(findCondition.getDailyId(),user.getUserId());
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("查询数据失败，请联系管理员!");
			return jsonResult;
		}

		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		if (list == null ) {

			jsonResult.setMsg("获取日报信息为空!");
			jsonResult.setData(new DecorationDailyInf());
			return jsonResult;
		}

		jsonResult.setCount(1);
		jsonResult.setMsg("获取日报信息成功!");
		jsonResult.setData(list);
		return jsonResult;

	}

	@RequestMapping(value = "/daily/search", method = RequestMethod.POST)
	public JsonResult dailybySearch(JsonResult jsonResult, @RequestBody DecorationDailyInf findCondition, HttpServletRequest request) {
		//校验用户信息
		String userid = null;
		try {
			userid = (String)request.getSession().getAttribute(Global.SESSION_USER_ID);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(StringUtils.isEmpty(userid)){
			jsonResult.setCode(JsonResult.FAILED_UNLGIN);
			jsonResult.setMsg("无用户登录信息,跳转登录页面");
			return jsonResult;
		}
		log.info("登录用户id未: " + userid);
		DecorationUser user = decUserService.findById(userid);
		if (user == null){
			jsonResult.setCode(JsonResult.FAILED_UNPERMISSION);
			jsonResult.setMsg("无用户信息,此用户无权限，跳转登录页面");
			return jsonResult;
		}
		findCondition.setUserId(user.getUserId());
		//获取日报信息
		DecorationDailyInf list = null;
		try {
			list = decDailyService.searchByCurDate(findCondition);
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("查询数据失败，请联系管理员!");
			return jsonResult;
		}

		if (list == null ) {
			jsonResult.setCode(JsonResult.SUCCESS_CODE);
			jsonResult.setMsg("获取日报信息为空!");
			jsonResult.setData(new DecorationDailyInf());
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setCount(1);
		jsonResult.setMsg("获取日报信息成功!");
		jsonResult.setData(list);
		return jsonResult;

	}

//    用户新增日报内容
	@RequestMapping(value = "/daily/add", method = RequestMethod.POST)
	public JsonResult dailyadd( HttpServletRequest req, JsonResult jsonResult, @RequestBody DecorationDailyInf inf) {
		// 用户信息校验必须是师傅类型或者监理
		String userid = (String)req.getSession().getAttribute(Global.SESSION_USER_ID);
		if (userid == null){
			userid = "aefe5ae774c3403fad0423fd24f8d13f";//测试专用
		}
		DecorationUser userinfo = decUserService.findById(userid);
		if (userinfo == null || !(userinfo.getPerType() == 1 || userinfo.getPerType() == 2) ) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("新增日报失败!当前用户无权限新增日报");
			return jsonResult;
		}
		inf.setDailyType(1);
		if (userinfo.getPerType() == 2){
			inf.setDailyType(2);
		}

		inf.setSupDailyFlag(userinfo.getPerType());

		// 时间校验，必须在当天
		String currentdate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
		inf.setCurrentDate(currentdate);  //上传日期

		inf.setDailyFlag(0); //可修改标识 0-可修改
        //插入日报内容
		inf.setUserId(userid);  //上报人id

		String dailyid = String.valueOf(SnowFlake.getInstance().nextId());
		inf.setDailyId(dailyid);          //日报id

		inf.setCreateId(userinfo.getUserId());  //创建人id
		inf.setCreateTime(new Date());
		inf.setUpdateId(userinfo.getUserId());  //更新人id
		inf.setUpdateTime(new Date());

		// 日报内容处理
		jsonResult = decDailyService.add(inf);

		return jsonResult;
	}

//    用户修改日报内容，只可修改当天日报
	@RequestMapping(value = "/daily/modify", method = RequestMethod.POST)
	public JsonResult dailymodify(HttpServletRequest req, JsonResult jsonResult, @RequestBody DecorationDailyInf ddi) {
		// 用户信息校验必须是师傅类型或者监理
		String userid = null;
		try {
			userid = req.getSession().getAttribute(Global.SESSION_USER_ID).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (userid == null){
			/*userid = "aefe5ae774c3403fad0423fd24f8d13f";//测试专用*/
			jsonResult.setCode(JsonResult.FAILED_UNLGIN);
			jsonResult.setMsg("无用户登录信息,跳转登录页面");
			return jsonResult;
		}
		DecorationUser userinfo = decUserService.findById(userid);
		if (!(userinfo.getPerType() == 1 || userinfo.getPerType() == 2 )) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("修改日报失败!当前用户无权限修改日报");
			return jsonResult;
		}
		ddi.setUpdateId(userinfo.getUserId());

		//校验参数
		if (StringUtils.isEmpty(ddi.getDailyId())){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("修改日报失败!未上送日报信息");
			return jsonResult;
		}

		//更新日报内容
		int result = 0;
		try {
			result = decDailyService.update(ddi);
		} catch (Exception e) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setCount(0);
			jsonResult.setMsg("修改日报信息异常!");
			jsonResult.setData(null);
			return jsonResult;
		}

		if ( result == 0){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("修改日报失败!");
			return jsonResult;
		}else if(result == 2){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("已过日报上送日期，不可修改!");
			return jsonResult;
		}else if(result == 3){
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("无此日报信息!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setCount(0);
		jsonResult.setMsg("修改日报列表成功!");
		jsonResult.setData(null);
		return jsonResult;
	}

}
